package com.jerome.fs.util;

import com.jerome.fs.constants.AppConstant;
import com.jerome.fs.storage.ExpiringMap;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Utility class for managing locks.
 * Provides methods for obtaining and managing locks based on data IDs.
 * Uses an expiring map to store locks.
 * @author Jerome
 * @date 2023/9/7
 */
public class LockUtil {
    public LockUtil(long time) {
        this.lockMap = new ExpiringMap<>(time);
    }

    /**
     * Lock map.
     * Key: data ID
     * Value: ReentrantLock object (Fair lock)
     */
    private volatile ExpiringMap<String, ReentrantLock> lockMap;

    /**
     * Get a ReentrantLock based on the provided data ID.
     *
     * @param id Data ID
     * @return ReentrantLock (Fair lock)
     */
    public synchronized ReentrantLock getReentrantLock(String id) {
        ReentrantLock lock = lockMap.get(id);
        if (lock == null) {
            // Create a new Fair lock
            lock = new ReentrantLock(true);
            lockMap.put(id, lock);
        }
        return lock;
    }
}
